<template>
  <div class="page-miH page-bgBack">
    <PageHeader v-if="type" @back="$router.go(-1)" subTitle="返回">
      <span v-if="type == '4'">入职模板设置</span>
      <span v-if="type == '5'">待入职模板设置</span>
    </PageHeader>
    <div v-if="!type" style="padding-left: 24px">
      <a-tabs @change="callback" v-model="typeKey">
        <a-tab-pane key="1" tab="入职模板"></a-tab-pane>
        <a-tab-pane key="2" tab="待入职模板"></a-tab-pane>
        <a-tab-pane key="3" tab="预登记模板"></a-tab-pane>
      </a-tabs>
    </div>
    <div style="padding: 24px 24px 12px 24px">
      <a-row>
        <a-col :span="16">
          <a-input-search placeholder="请输入模板/编辑人名称" v-model="name" style="width: 200px" @search="onSearch" />
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-button type="primary" v-if="!type && typeKey != '3'" @click="issueTemplate">下发模板</a-button>
          <a-button type="primary" style="margin-left: 5px" icon="plus" @click="newTemplate">创建模板</a-button>
        </a-col>
      </a-row>
    </div>
    <!-- 底部 -->
    <div>
      <a-spin :spinning="spinning">
        <div style="padding-right: 15px">
          <a-row>
            <a-col :span="6" v-for="i in entities" :key="i.id">
              <div class="temBox">
                <div style="padding: 24px 14px 24px 24px">
                  <a-row style="margin-bottom: 12px">
                    <a-col :span="20">
                      <span class="temTitle">{{ i.name }}</span>
                      <span class="temTitleStatus" v-if="i.isDefault">默认</span>
                      <span class="temTitleStatus temTitleStatus1" v-if="i.isIssue">下发</span>
                    </a-col>
                    <a-col :span="4" class="temRig">
                      <span class="temRigSpanHove">
                        <span class="temRigSpan"></span>
                        <span class="temRigSpan"></span>
                        <span class="temRigSpan"></span>

                        <div class="temRigSpanBoxSHow">
                          <p class="temRigP" @click="editTemplates(i)">编辑</p>
                          <p class="temRigP" v-if="!i.isDefault" @click="customTemplatesDel(i.id)">删除</p>
                        </div>
                      </span>
                    </a-col>
                  </a-row>
                  <div class="temEdit">
                    <span class="temEditWid">编辑人:</span>
                    {{ i.editBy }}
                  </div>
                  <div class="temEdit">
                    <span class="temEditWid">编辑时间:</span>
                    {{ moment(i.gmtModified).format("YYYY-MM-DD HH:mm:ss") }}
                  </div>
                </div>
                <div style="border-top: 1px solid #e8e8e8" v-if="type || typeKey === '3'">
                  <div class="temBoxBottom">
                    <a-switch v-model="i.isOpen" @change="(e) => isOpenChange(e, i)">
                      <a-icon slot="checkedChildren" type="check" />
                      <a-icon slot="unCheckedChildren" type="close" />
                    </a-switch>
                    <span class="temBoxBottomShow">{{ i.isOpen ? "已启用" : "停用" }}</span>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
        <div style="position: fixed; bottom: 35px; right: 25px">
          <a-pagination
            :defaultPageSize="8"
            v-model="current"
            @change="onChange"
            :total="total"
            :show-total="(total) => `共 ${total} 条`"
            show-quick-jumper
          />
        </div>
      </a-spin>
    </div>
    <!-- 弹出框 -->
    <a-modal
      title="下发模板"
      :visible="visible"
      :destroyOnClose="true"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <a-form :form="form" class="antClassSelectHei">
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="选择模板">
          <a-select
            option-filter-prop="children"
            show-search
            :filter-option="filterOption"
            style="width: 100%"
            placeholder="请选择模板"
            v-decorator="['templateId', { rules: [{ required: true, message: '请选择模板' }] }]"
          >
            <a-select-option :value="i.id" v-for="i in templateEntities" :key="i.id">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="用工单位">
          <a-tree-select
            placeholder="请选择用工单位"
            v-decorator="['companyList', { rules: [{ required: true, message: '请选择用工单位' }] }]"
            :tree-data="dataList"
            :filterTreeNode="false"
            @search="treeSearch"
            :replaceFields="replaceFields2"
            @change="treeSelectChange"
            labelInValue
            tree-checkable
            style="width: 200px; margin-top: 10px; max-height: 350px"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
// type有值代表用工单位分别为4和 5 代表入职和待入职。   type没有代表租户 三个tabs 展示typeKey代表
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 10 }
};
const formTailLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 10, offset: 4 }
};
import { customTemplates, customTemplatesOpen, customTemplatesDel, issueTemplate } from "./api";
import { findCompanyGroup } from "@/api/company/contract";
export default {
  data() {
    return {
      replaceFields2: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      },
      companyList: [],
      dataList: [],
      templateEntities: [],
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this, { name: "dynamic_rule" }),
      visible: false,
      confirmLoading: false,
      flatDataList: [],
      entities: [],
      typeKey: "1",
      name: "",
      total: 0,
      current: 1,
      spinning: false
    };
  },
  computed: {
    type() {
      return this.$route.params.type;
    }
  },
  created() {},
  mounted() {
    this.typeKey = this.$route.query.openTab ? this.$route.query.openTab : "1";
    this.findCompanyGroup();
    this.customTemplatesFun();
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    // 递归处理为扁平数组
    flatten(list) {
      if (list !== null) {
        list.forEach((item) => {
          this.flatDataList.push(item);
          this.flatten(item.companyList);
        });
      }
    },
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        el.scopedSlots = { title: "custom" };
        this.addTreeSlot(el.companyList);
      });
      return data;
    },
    treeSelectChange(value, label, extra) {
      // console.log(value);
    },
    // 用工单位
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.dataList = this.addTreeSlot(res.data);
          this.flatten(this.dataList);
          this.form.setFieldsValue({
            companyList: this.form.getFieldValue("companyList") ? JSON.parse(JSON.stringify(this.form.getFieldValue("companyList"))) : null
          });
          // 每次查询树形数据后需要把树选择组件绑定的companyList深拷贝
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    editTemplates(i) {
      if (this.type) {
        this.$router.push({
          path: `/staff/edit/${i.moduleCode === "checkIn" ? "template_ydj" : "newTemplate"}`,
          query: { name: i.name, id: i.id, isDefault: i.isDefault, type: i.type, statusSHow: "3", status: "edit", moduleCode: i.moduleCode }
        });
      } else {
        this.$router.push({
          path: `/contractAdmin/ruzhi/${i.moduleCode === "checkIn" ? "template_ydj" : "newTemplate"}`,
          query: {
            name: i.name,
            id: i.id,
            isDefault: i.isDefault,
            type: i.type,
            statusSHow: "2",
            status: "edit",
            moduleCode: i.moduleCode,
            openTab: this.typeKey
          }
        });
      }
    },
    // 下发模板
    issueTemplate() {
      this.visible = true;
      let moduleCode = null;
      let type = null;

      if (this.type) {
        moduleCode = this.type === "4" ? "onJob" : "waitJob";
        type = 3;
      } else {
        moduleCode = this.typeKey === "1" ? "onJob" : this.typeKey === "2" ? "waitJob" : "checkIn";
        type = 2;
      }
      const data = {
        companyId: this.type ? this.$store.state.hr.companyId : null,
        type: type,
        moduleCode: moduleCode,
        "orders[0].property": "gmtCreate",
        "orders[0].desc": true
      };
      customTemplates(Object.assign(data, { pageNo: 1, pageSize: 999 }))
        .then((res) => {
          this.templateEntities = res.data.entities;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 下发模板 确定
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const companyArr = [];
          values.companyList.forEach((item) => {
            this.flatDataList.forEach((item2, index2) => {
              if (item2.uuid && item2.uuid === item.value) {
                companyArr.push({ subjectId: item2.id, subjectName: item2.name });
              }
            });
          });
          const data = {
            templateId: values.templateId,
            companyIdList: [...new Set(companyArr.map((z) => z.subjectId))]
          };
          // if (data.companyIdList.length > 5) {
          //   this.$message.error("单次下发模版时，最多可选择5条模版!");
          //   return;
          // }
          this.confirmLoading = true;
          issueTemplate(data)
            .then((res) => {
              this.$message.success(res.msg);
              this.confirmLoading = false;
              this.visible = false;
            })
            .catch((err) => {
              this.confirmLoading = false;
              console.log(err);
            });
        }
      });
    },
    // 删除
    customTemplatesDel(id) {
      const that = this;
      this.$confirm({
        title: "确定要删除?",
        onOk() {
          that.customTemplatesDelFun(id);
        },
        onCancel() {}
      });
    },
    customTemplatesDelFun(id) {
      customTemplatesDel(id)
        .then((res) => {
          this.$message.success(res.msg);
          this.customTemplatesFun();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 启用
    isOpenChange(val, event) {
      if (!val) {
        this.$message.error("请先选择一个模板开启");
        this.customTemplatesFun();
        return;
      }
      const data = {
        companyId: this.type ? this.$store.state.hr.companyId : "site",
        templateId: event.id
      };
      customTemplatesOpen(data)
        .then((res) => {
          this.$message.success(res.msg);
          this.customTemplatesFun();
        })
        .catch((err) => {
          console.log(err);
          this.customTemplatesFun();
        });
    },
    customTemplatesFun() {
      // onJob 入职 waitJob,待入职 checkIn预登记
      let moduleCode = null;
      let type = null;
      if (this.type) {
        moduleCode = this.type === "4" ? "onJob" : "waitJob";
        type = 3;
      } else {
        moduleCode = this.typeKey === "1" ? "onJob" : this.typeKey === "2" ? "waitJob" : "checkIn";
        type = 2;
      }
      const data = {
        companyId: this.type ? this.$store.state.hr.companyId : null,
        type: type,
        pageSize: 8,
        name: this.name,
        pageNo: this.current,
        moduleCode: moduleCode,
        "orders[0].property": "gmtCreate",
        "orders[0].desc": true
      };
      this.spinning = true;
      customTemplates(data)
        .then((res) => {
          this.spinning = false;
          this.entities = res.data.entities;
          this.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onChange(pageNumber) {
      this.current = pageNumber;
      this.customTemplatesFun();
    },
    callback(key) {
      this.current = 1;
      this.typeKey = key;
      this.customTemplatesFun();
    },
    onSearch(value) {
      this.current = 1;
      this.customTemplatesFun();
    },
    newTemplate() {
      let moduleCode = null;
      let type = null;
      if (this.type) {
        moduleCode = this.type === "4" ? "onJob" : "waitJob";
        type = 3;
      } else {
        moduleCode = this.typeKey === "1" ? "onJob" : this.typeKey === "2" ? "waitJob" : "checkIn";
        type = 2;
      }
      if (this.type) {
        this.$router.push({
          path: `/staff/edit/${moduleCode === "checkIn" ? "template_ydj" : "newTemplate"}`,
          query: { type: type, statusSHow: "3", status: "add", moduleCode: moduleCode }
        });
      } else {
        this.$router.push({
          path: `/contractAdmin/ruzhi/${moduleCode === "checkIn" ? "template_ydj" : "newTemplate"}`,
          query: { type: type, status: "add", moduleCode: moduleCode, statusSHow: "2", openTab: this.typeKey }
        });
      }
    }
  }
};
</script>
<style>
.antClassSelectHei .ant-select-selection {
  max-height: 90px;
  overflow-y: auto;
}
</style>
<style scoped>
.temRigSpanBoxSHow {
  width: 80px;
  position: absolute;
  left: 6px;
  z-index: 1;
  display: none;
  background: #fff;
  box-shadow: 0px 2px 7px 0px rgba(0, 0, 0, 0.15);
}
.temRigSpanHove {
  display: inline-block;
}
.temRigSpanHove:hover .temRigSpanBoxSHow {
  display: block;
}
.temRigSpanHove:hover .temRigSpan {
  background: #6a66f6;
}
.temBox {
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  margin: 12px 0px 12px 24px;
}
.temBox:hover {
  background: #ffffff;
  box-shadow: 0 4px 12px 0 rgba(106, 102, 246, 0.1);
  border-radius: 4px;
  border: 1px solid #ffffff;
}
.temBox:hover .temRigSpan {
  background: #6a66f6;
}
.temTitle {
  font-size: 16px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
  color: #3c3d43;
  max-width: 59%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: inline-block;
  vertical-align: bottom;
}
.temTitleStatus {
  border-radius: 2px;
  border: 1px solid #32ccaa;
  width: 42px;
  height: 16px;
  font-size: 10px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
  color: #32ccaa;
  line-height: 15px;
  border-radius: 2px;
  margin-left: 8px;
  text-align: center;
  display: inline-block;
}
.temTitleStatus1 {
  border: 1px solid #ffbb00;
  color: #ffbb00;
}
.temEdit {
  margin-top: 12px;
  font-size: 14px;
  font-family: SourceHanSansCN-Regular, SourceHanSansCN;
  color: #55565d;
}
.temBoxBottom {
  height: 48px;
  /* border-top: 1px solid #e8e8e8; */
  padding: 0 14px 0 24px;
  line-height: 45px;
}
.temBoxBottomShow {
  font-size: 14px;
  margin-left: 10px;
  font-family: SourceHanSansCN-Regular, SourceHanSansCN;
  color: #a6a8b4;
}
.temEditWid {
  width: 65px;
  text-align: left;
  display: inline-block;
}
.temRig {
  cursor: pointer;
  text-align: right;
  padding-right: 2px;
}
.temRigSpan {
  width: 4px;
  height: 4px;
  background: #ebedf0;
  /* background: #6a66f6; */
  border-radius: 50%;
  display: inline-block;
  margin: 0 2px;
}
/* .temRig:hover .temRigSpan {
  background: #6a66f6;
}
.temRigA:hover .temRigSpan {
  background: #6a66f6;
} */
.temRigP {
  width: 80px;
  height: 36px;
  line-height: 36px;
  color: #55565d;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  margin-bottom: 0;
}
.temRigP:hover {
  background: rgba(106, 102, 246, 0.16);
  color: #6a66f6;
}
</style>
